package com.daidai.activitys

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.SurfaceHolder
import android.view.SurfaceView
import com.daidai.base.BaseActivity
import com.daidai.spinner.R
import com.daidai.tools.G

class GameView @JvmOverloads constructor(
        ctx: Context,
        attrs: AttributeSet? = null,
        defStyle: Int = 0) : SurfaceView(ctx, attrs, defStyle), SurfaceHolder.Callback ,Runnable{

    var loop = false
    var thread:Thread? = null
    var paint:Paint
    var lastMs = -1L

    lateinit var bgBitmap:Bitmap

    init {
        holder.addCallback(this)
        paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint.color = Color.RED
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        G.elog("surfaceCreated called!")
        loop = true
        thread = Thread(this).apply { start() }

    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        G.elog("surfaceChanged called! format:$format,width:$width,height:$height")
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        G.elog("surfaceDestroyed called!")
        loop = false
    }

    override fun run() {
        while (loop && !Thread.currentThread().isInterrupted){
            Thread.sleep(10)
            synchronized(holder){
                render()
            }
        }
    }
    private fun render(){
        if(lastMs < 0){
            lastMs = System.currentTimeMillis()
            return
        }

        var curMs = System.currentTimeMillis()
        var durationMs = curMs - lastMs
        lastMs = curMs

        val canvas = holder.lockCanvas()
        canvas?.let {ctx->

//            ctx.drawBitmap()

            ctx.drawColor(Color.GREEN)
            ctx.drawCircle(100f,100f,30f,paint)
            G.elog("time:$durationMs")
            holder.unlockCanvasAndPost(ctx)
        }
    }


}


class SurfaceActivity : BaseActivity() {

    lateinit var gameView: GameView

    override fun getContentViewResId() = R.layout.activity_surface
    override fun initView() {
        gameView = findViewById(R.id.gameView)
    }

    override fun initData() {
    }
}